// var base_url = 'http://39.105.19.58:8092/xmsc';
Vue.component('chat_room', {
  template: `<div>
  <div class="chatRoom_wrap" >
    <!-- <div class="return_page" @click="return_page">关闭</div> -->
    <div class="return_page" @click="return_page">关闭</div>
    <div class="wrapMain">
      <div class="sidebar">
        <div class="card">
          <header>
            <img class="avatar" width="40" height="40" alt="coffce" :src="adminLogo" :key="adminLogo+1">
            <p class="name">{{ryName}}</p>
          </header>
          <footer>
            <!-- <input class="search" type="text" placeholder="search user..." v-model="serchData"> -->
          </footer>
        </div>
        <div class="list">
          <ul>
            <li :class="item.check?'active':''" v-for="(item,index) in chatList" :key="index" @click="select(item.targetId,index)">
              <el-badge :value="item.unreadMessageCount" class="item" :hidden="item.unreadMessageCount==0">
                <img class="avatar" width="30" height="30" :src="item.ryIcon?item.ryIcon:'https://jkytest.oss-cn-beijing.aliyuncs.com/staticimg/00touxiang_blue.jpg'" :key="item.ryIcon+index">
              </el-badge>
              <p class="name">{{item.ryName?item.ryName:'陌生人'}}</p>
            </li>
          </ul>
        </div>
      </div>
      <div class="main">
        <div class="message">
          <ul v-for="(item,index) in chatList" :key="index" v-if="item.check">

            <li v-for="(checkitem,checkindex) in item.record" :key="checkindex">
              <p class="time">
                <span>{{checkitem.sentTime}}</span>
              </p>
              <div class="other" :class="checkitem.senderUserId==userId?'self':''">
                <img class="avatar" width="30" height="30" :src="adminLogo" :key="adminLogo+index" v-if="checkitem.senderUserId==userId">
                <img class="avatar" width="30" height="30" :src="item.ryIcon" :key="item.ryIcon+index" v-if="checkitem.senderUserId!=userId">

                <div class="text">
                  <p v-if="checkitem.messageType=='TextMessage'" v-html="checkitem.content.content">

                  </p>
                  <div class="img" v-if="checkitem.messageType=='ImageMessage'">
                    <img :src="checkitem.content.imageUri" alt="">
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </div>
        <div class="chartGroup">
          <el-upload class="img-upload" style="display:none" :action="sevarUrl" :on-remove="upremove" :on-success="upSuccess" :before-upload="beforeAvatarUpload">
          </el-upload>
          <i class="iconfont icon-fasongtupian" @click="upload"></i>
          <el-popover :visible-arrow=false  placement="top"  width="400" trigger="click" content=""  >
            <!-- <el-button slot="reference">content</el-button> -->
            <div>
              <span v-for="(item,index) in list" :key="index" class="point" @click="selectEmoil(item)" v-html="item.node"></span>
            </div>
            <!-- <el-button type="text" slot="reference">表情</el-button> -->
            <i class="iconfont icon-smile" slot="reference"></i>
          </el-popover>

        </div>
        <div id="text">
          <textarea placeholder="按 Ctrl + Enter 发送" @keyup.ctrl.13="sumbit()" v-model="text"></textarea>
          <el-button type="info" class="fr" style="margin-right:10px;" plain @click="sumbit()" size="mini">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</div>
`,
  props: {
    firmIm:{
      type:null,
      default:''
    },
    // 'string':[String]
  },
  data() {
    return {
      token: localStorage["ryToken"],
      self: null,
      adminTitle: "",
      name: "",
      text: "",
      list: null,
      serchData: "",
      sevarUrl: "http://39.96.36.44:8080/xmsc/upload/singleUploadImg", // 这里写你要上传的图片服务器地址
      adminLogo: localStorage["ryIcon"],
      userId: "",
      ryName: "加载中...",
      personlOne: "../../static/2.png",
      activeIndex: 0,
      chatList: [],
      targetId: null,
      chatRecord: [
        {
          id: "1",
          avarLogo: "../../static/1.jpg",
          status: 1,
          content:
            "Hello，这是一个基于Vue + Vuex + Webpack构建的简单chat示例，聊天记录保存在localStorge, 有什么问题可以通过Github Issue问我",
          img: "../../static/1.jpg"
        }
      ],
      selectList: [],
      checkAll: false,
      alldata: {
        list: []
      },
      ipt: "",
      tab: 0,
      // firmIm: "",
      type:'',
      base64Data:'',
      chatroom_block:true,
      store:''
    };
  },
  created(){
    // this.targetId = this.firmIm
    // this.sendHello(this,this.targetId)
  },
  watch: {
    firmIm:function(newValue,oldValue) {
      console.log(newValue,oldValue)
      this.sendHello(this,newValue)
    }
  },
  mounted() {
    
    console.log(this.firmIm + '111111111111111111111111')
    // this.firmIm = GetQueryString().firmIm
    // console.log('firmIm='+ this.firmIm)
    // var targetId  = this.firmIm
    var appKey = "lmxuhwaglilud";
    var token = this.token;
    RongIMLib.RongIMClient.init(appKey);


    var that = this;
    //聊天功能注释
 
    /**
     * 融云连接状态监听
     */
    RongIMClient.setConnectionStatusListener({
      onChanged: function(status) {
        switch (status) {
          case RongIMLib.ConnectionStatus.CONNECTED:
            //判断是否有GetQueryString().firmIm逻辑处理
            if (
              that.firmIm &&
              that.firmIm != undefined
            ) {
              that.firmIm = that.firmIm;
              // that.sendHello(that);
              console.log(that.firmIm)
                  if(that.firmIm!=''){
                    that.sendHello(that,that.firmIm)
                  }
            } else {
              if(that.chatList.length>0){
                that.firmIm = chatList[that.activeIndex].targetId;
              }
              that.getConversationList(that);
            }
            that.getUnreadCount();
            that.getTotalUnreadCount();
            break;
          case RongIMLib.ConnectionStatus.CONNECTING:
            console.log("正在链接");
            break;
          case RongIMLib.ConnectionStatus.DISCONNECTED:
            console.log("断开连接");
            break;
          case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
            console.log("其他设备登录");
            break;
          case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
            console.log("域名不正确");
            break;
          case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
            console.log("网络不可用");
            break;
        }
      }
    });


    // 消息监听器
    RongIMClient.setOnReceiveMessageListener({
      // 接收到的消息
      onReceived: function(message) {
        // that.getConversationList(that)
        // 判断消息类型
        // if (that.$route.name == "消息提醒") {
        // if (message.senderUserId == GetQueryString().firmIm) {
        console.log(message.content.content);
        
        if (message.content.content != "") {
          that.scrollListDown();
          switch (message.messageType) {
            case RongIMClient.MessageType.TextMessage:
              that.$notify({
                message: message.senderUserId + "发来一条文字信息",
                type: "success",
                onClick: function() {
                  that.$emit("forroom", true);
                }
              });
              var off = false;
              console.log(that.chatList)
              for (let n = 0; n < that.chatList.length; n++) {
                if (that.chatList[n].targetId == message.senderUserId) {
                  console.log(that.chatList[n])
                  off = true;
                  message.sentTime = timeFormatNotime(message.sentTime);
                  message.content.content = RongIMLib.RongIMEmoji.emojiToHTML(
                    RongIMLib.RongIMEmoji.symbolToEmoji(message.content.content)
                  );
                  console.log(that.chatList[n])
                  if (
                    that.chatList[n].record == undefined ||
                    that.chatList[n].record == null
                  ) {
                    that.chatList[n].record = [];
                    //获取自己服务器上的头像和昵称
                    axios({
                      method:"POST",
                      url:base_url + "/rongyun/getInfo",
                      data:Qs.stringify({
                        userId: that.chatList[n].targetId
                      }),
                      headers:{
                          'Content-Type':'application/x-www-form-urlencoded',
                          "TOKEN":localStorage.getItem('wACCESS_TOKEN')
                      }
                      })
                      .then(function (response) {
                        var mydata = that.chatList[n];
                        if (response.data.msg == "success") {
                          mydata.ryName = response.data.data.ryInfo.ryName;
                          mydata.ryIcon = response.data.data.ryInfo.ryIcon;
                        } else {
                          mydata.ryName = "获取失败";
                          mydata.ryIcon = "";
                        }
                        that.$set(that.chatList, n, mydata);
                      })
                      .catch(function (error) {
                          console.log(error);
                      });
                   
                  }
                  console.log(that.chatList[n])
                  var record = that.chatList[n];
                  console.log(record)
                  record.record.push(message);
                  console.log(that.chatList[n])
                  // that.getConversationList(that);
                  that.$set(that.chatList, n, record);
                }
              }
              if (that.chatList.length == 0) {
                that.getHistroyMessage(that);
              }
              if (!off) {
                console.log("重新获取");  
                that.firmIm = message.senderUserId;
                that.getConversationList(that);
                that.getHistroyMessage(that);
              }
              that.scrollTop();
              // that.text = "收到消息";
              that.text = "";
              // alert(1);
              // message.content.content => 消息内容
              break;
            case RongIMClient.MessageType.VoiceMessage:
              // 对声音进行预加载
              // message.content.content 格式为 AMR 格式的 base64 码
              that.$notify({
                message: "您收到一条语音消息",
                type: "success"
              });
              for (let n = 0; n < that.chatList.length; n++) {
                if (that.chatList[n].targetId == message.senderUserId) {
                  message.sentTime = timeFormatNotime(message.sentTime);
                  var record = that.chatList[n];
                  record.record.push('暂不支持语音消息，请前往展派app查看');
                    // that.chatList[n].record.push(message);
                  that.$set(that.chatList, n, record);
                }
              }
              // setTimeout(function(){
              that.scrollTop();
              // },1000)
              break;
            case RongIMClient.MessageType.ImageMessage:
              that.$notify({
                message: message.senderUserId + "发来一条图片信息",
                type: "success"
              });
              for (let n = 0; n < that.chatList.length; n++) {
                if (that.chatList[n].targetId == message.senderUserId) {
                  message.sentTime = timeFormatNotime(message.sentTime);
                  var record = that.chatList[n];
                  record.record.push(message);
                  // that.chatList[n].record.push(message);
                  that.$set(that.chatList, n, record);
                }
              }
              // setTimeout(function(){
              that.scrollTop();
              // },1000)

              // message.content.content => 图片缩略图 base64。
              // message.content.imageUri => 原图 URL。
              break;
            case RongIMClient.MessageType.DiscussionNotificationMessage:
              // message.content.extension => 讨论组中的人员。
              break;
            case RongIMClient.MessageType.LocationMessage:
              // message.content.latiude => 纬度。
              // message.content.longitude => 经度。
              // message.content.content => 位置图片 base64。
              break;
            case RongIMClient.MessageType.RichContentMessage:
              // message.content.content => 文本消息内容。
              // message.content.imageUri => 图片 base64。
              // message.content.url => 原图 URL。
              break;
            case RongIMClient.MessageType.InformationNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.ContactNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.ProfileNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.CommandNotificationMessage:
              // do something...
              break;
            case RongIMClient.MessageType.CommandMessage:
              // do something...
              break;
            case RongIMClient.MessageType.UnknownMessage:
              // do something...
              break;
            default:
            // do something...
          }
        } else {
          that.$notify({
                message:  "暂无新消息",
                type: "success"
              });
          that.getConversationList(that);
          that.scrollListTop();
        }
      }
      // } else {
      //   that.$notify({
      //     title: "提示",
      //     message: "你有新的消息,请前往聊天室查看",
      //     type: "success"
      //   });
      // }
      // }
    });

    /**
     *连接融云
     */
    RongIMClient.connect(
      that.token,
      {
        onSuccess: function(userId) {
          that.userId = userId;
          that.ryName = localStorage["ryName"];
          // that.$store.commit({
          //   type: "get_rcloud_userId",
          //   userid: userId
          // });
          var callback = {
            onSuccess: function(userId) {
              that.userId = userId;
              that.ryName = localStorage["ryName"];
              that.$store.commit({
                type: "get_rcloud_userId",
                userid: userId
              });
              // localStorage.setItem['ry_userId'] = userId
            },
            onTokenIncorrect: function() {
              that.reset(that);
            },
            onError: function(errorCode) {
              console.log(errorcode);
            }
          };
          var config = {
            // 默认 false, true 启用自动重连，启用则为必选参数
            auto: true,
            // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
            url: "cdn.ronghub.com/RongIMLib-2.2.6.min.js",
            // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
            rate: [100, 1000, 3000, 6000, 10000]
          };
          RongIMClient.reconnect(callback, config);
        },
        onTokenIncorrect: function() {
          that.reset(that);
        },
        onError: function(errorCode) {
          var info = "";
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = "超时";
              break;
            case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
              info = "不可接受的协议版本";
              break;
            case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
              info = "appkey不正确";
              break;
            case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
              info = "服务器不可用";
              break;
          }
          console.log(errorCode);
        }
      }
    );
    //聊天功能注释
  },
  created() {
    this.list=RongIMLib.RongIMEmoji.list
    this.period()
  },
  destroyed() {
    var start = new Date().getTime();
    RongIMClient.getInstance().disconnect(); //聊天功能注释
  },
  methods: {
    period() {
      axios({
          method:"POST",
          url:base_url + "/rongyun/getInfo",
          data:Qs.stringify({
              userId:localStorage.getItem('userId')
          }),
          headers:{
              'Content-Type':'application/x-www-form-urlencoded',
              "TOKEN":localStorage.getItem('wACCESS_TOKEN')
          }
      })
      .then(function (res) {
        console.log(res.data)
        this.ryIcon = res.data.data.ryInfo.ryIcon
        this.ryName = res.data.data.ryInfo.ryName
        localStorage.setItem("ryName",res.data.data.ryInfo.ryName)
        // this.ryIcon = res.data.data.ryInfo.ryIcon
        console.log('融云登录')
      })
      .catch(function (error) {
          console.log(error);
      });
  },
    return_page(){
      // this.chatroom_block = false
      this.$emit("forroom", false);
      //  this.$router.go(-1)
    },
    beforeAvatarUpload(file) {
      var that = this;
      if (this.chatList.length < 1) {
        this.$notify({
          title: "提示",
          message: "您暂无会话",
          type: "success"
        });
        return false;
      }
      this.type = file.type;
      this.file = file;
      const isJPG = file.type === "image/jpeg";
      console.log(file.size);
      const isLt100 = file.size / 1024 / 100 < 1;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt100) {
        this.$message.error("上传图片大小不能超过 100k!");
      }
      return isJPG && isLt100;
    },
    reset(that) {
      // that.$ajax
      //   .post(
      //     that.$api + "/rongyun/getToken",
      //     that.qs.stringify({
      //       ryId: localStorage["ryId"]
      //     })
      //   )
      //   .then(response => {
      //     if (response.data.msg == "success") {
      //       that.token = response.data.data.ryToken;
      //       console.log(response);
      //       RongIMClient.reconnect({
      //         onSuccess: function(msg) {
      //           console.log(msg);
      //           that.userId = userId;
      //           that.ryName = localStorage["ryName"];
      //           that.$store.commit({
      //             type: "get_rcloud_userId",
      //             userid: userId
      //           });
      //           //重连成功
      //         },
      //         onError: function(error) {
      //           //重连失败
      //           console.log(error);
      //         }
      //       });
      //     } else {
      //     }
      //   })
      //   .catch(function(error) {
      //     console.log(error);
      //   });
    },

    reconnect() {
      /*
	1: reconnect 是重新连接，并没有重连机制，调用此方法前应该进行网络嗅探，网络正常再调用 reconnect。
	2: 提示其他设备登录请勿调用重连方法。
 	3: docs   http://www.rongcloud.cn/docs/api/js/RongIMClient.html
  */

      var that = this;
      var start = new Date().getTime();
      begin = new Date().getTime();
      RongIMClient.reconnect({
        onSuccess: function(userId) {},
        onTokenIncorrect: function() {
          that.reset(that);
        },
        onError: function(errorCode) {
          var info = "";
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = "超时";

              break;
            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
              info = "未知错误";
              break;
            case RongIMLib.ErrorCode.UNACCEPTABLE_PROTOCOL_VERSION:
              info = "不可接受的协议版本";
              break;
            case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
              info = "appkey不正确";
              break;
            case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
              info = "服务器不可用";
              break;
          }
        }
      });
    },
    /**
     * 获取新消息数量
     * param(token)  变量token=>即token
     */
    getMessageNum(token) {
      RongIMClient.getInstance().hasRemoteUnreadMessages(token, {
        onSuccess: function(hasMessage) {
          if (hasMessage) {
            that.$notify({
              title: "提示",
              message: "你有新的消息,请前往聊天室查看",
              type: "success"
            });
            /**
             * 获取未读消息方法
             */
            RongIMClient.getInstance().getTotalUnreadCount({
              onSuccess: function(count) {
                console.log(count);
                // count => 所有会话总未读数。
              },
              onError: function(error) {
                // error => 获取总未读数错误码。
              }
            });
          } else {
            // 没有未读的消息
            that.$notify({
              title: "提示",
              message: "没有未读的消息",
              type: "success"
            });
          }
        },
        onError: function(err) {
          // 错误处理...
        }
      });
    },
    handleCheckAllChange(val) {
      this.alldata.list.map((item, i) => {
        item.checkModel = val;
      });
    },
    //删除
    alldel() {
      this.alldata.list.map((item, i) => {
        if (item.checkModel == true) {
          this.selectList.push(item.id);
        }
      });
      if (this.selectList.length == 0) {
        this.$message({
          message: "您暂无勾选删除项",
          type: "warning"
        });
      } else {
        this.selectList.toString();
        axios({
          method:"POST",
          url:base_url + "/me/dM",
          data:Qs.stringify({
            id: this.selectList.toString()
          }),
          headers:{
              'Content-Type':'application/x-www-form-urlencoded',
              "TOKEN":localStorage.getItem('wACCESS_TOKEN')
          }
          })
        .then(function (response) {
          if (response.data.msg == "success") {
            let selected = [];
            this.alldata.list.map((item, i) => {
              if (item.checkModel == false) {
                selected.push(item);
              }
            });
            this.alldata.list = selected;
            this.$message({
              message: "删除成功",
              type: "success"
            });
          } else {
          }
        })
        .catch(function (error) {
            console.log(error);
        });
        // this.$ajax
        //   .post(
        //     this.$api + "/me/dM",
        //     this.qs.stringify({
        //       id: this.selectList.toString()
        //     })
        //   )
        //   .then(response => {
        //     console.log(response.data.data);
        //     if (response.data.msg == "success") {
        //       let selected = [];
        //       this.alldata.list.map((item, i) => {
        //         if (item.checkModel == false) {
        //           selected.push(item);
        //         }
        //       });
        //       this.alldata.list = selected;
        //       this.$message({
        //         message: "删除成功",
        //         type: "success"
        //       });
        //     } else {
        //     }
        //   })
        //   .catch(function(error) {
        //     console.log(error);
        //   });
      }
    },
    singleDel(id, index) {
      // this.$ajax
      //   .post(
      //     this.$api + "/me/dM",
      //     this.qs.stringify({
      //       id: id
      //     })
      //   )
      //   .then(response => {
      //     console.log(response.data.data);
      //     if (response.data.msg == "success") {
      //       this.alldata.list.splice(index, 1);
      //       this.$message({
      //         message: "删除成功",
      //         type: "success"
      //       });
      //     } else {
      //     }
      //   })
      //   .catch(function(error) {
      //     console.log(error);
      //   });
    },
    handleCheckItemChange(val) {
      for (let i = 0, l = this.alldata.list.length; i < l; i++) {
        if (this.alldata.list[i].checkModel !== val) {
          this.checkAll = false;
          return;
        }
      }
      this.checkAll = val;
    },
    // gitData() {
    //   this.$ajax
    //     .post(
    //       this.$ajax + '/me/sAty',
    //       this.$qs.stringify({
    //         // userId: localStorage["user_id"]
    //       })
    //     )
    //     .then(response => {
    //       console.log(response)
    //       if (response.data.msg == 'success') {
    //         for (let n = 0; n < response.data.data.list.length; n++) {
    //           response.data.data.list[n].checkModel = false
    //         }
    //         this.alldata.list = response.data.data.list
    //         console.log(this.alldata.list)
    //       } else {}
    //     })
    //     .catch(function (error) {
    //       console.log(error)
    //     })
    // },
    tabclick(id) {
      this.tab = id;
    },
    selectEmoil(item) {
      console.log(item);
      this.text = this.text + item.emoji;
    },
    scrollTop() {
      setTimeout(function() {
        var s = document.querySelector(".message").clientHeight;
        var t = document.querySelector(".message ul").scrollHeight;
        var n = document.querySelector(".message ul").scrollTop;
        document.querySelector(".message").scrollTop = t;
      }, 500);

      // console.log(document.querySelector(".message").scrollTop);
      // console.log(s, t, n);
    },
    scrollListTop() {
      setTimeout(function() {
        var s = document.querySelector(".list").clientHeight;
        var t = document.querySelector(".list ul").scrollHeight;
        var n = document.querySelector(".list ul").scrollTop;
        document.querySelector(".list").scrollTop = t;
      }, 500);

      // console.log(document.querySelector(".message").scrollTop);
      // console.log(s, t, n);
    },
    scrollListDown() {
      setTimeout(function() {
        // var s = document.querySelector(".list").clientHeight;
        // var t = document.querySelector(".list ul").scrollHeight;
        // var n = document.querySelector(".list ul").scrollTop;
        document.querySelector(".list").scrollTop = 0;
      }, 500);

      // console.log(document.querySelector(".message").scrollTop);
      // console.log(s, t, n);
    },
    sendHello(that,newval) {
      console.log('建立成功')
      var msg = new RongIMLib.TextMessage({
        content: "你好",
        extra: "附加信息"
      });
      var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
      var targetId = newval?newval:that.firmIm; // 目标 Id
      
      console.log(targetId)
      RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
        onSuccess: function(message) {
          console.log("发送");
          that.getConversationList(that);
        },
        onError: function(errorCode, message) {
          var info = "";
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = "超时";
              break;
            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
              info = "未知错误";
              break;
            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
              info = "在黑名单中，无法向对方发送消息";
              break;
            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
              info = "不在讨论组中";
              break;
            case RongIMLib.ErrorCode.NOT_IN_GROUP:
              info = "不在群组中";
              break;
            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
              info = "不在聊天室中";
              break;
            default:
              info = x;
              break;
          }
        }
      });
    },
    sendTextMessage(textContent) {
      var that = this;
      var msg = new RongIMLib.TextMessage({
        content: textContent,
        extra: "附加信息"
      });
      console.log(that.firmIm)
      var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
      var targetId = that.firmIm; // 目标 Id
      RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
        onSuccess: function(message) {
          console.log(message);
          for (let i = 0; i < that.chatList.length; i++) {
            if (that.chatList[i].check) {
              message.sentTime = timeFormatNotime(message.sentTime);
              message.content.content = RongIMLib.RongIMEmoji.emojiToHTML(
                message.content.content
              );
              console.log(message);
              console.log(message.content.content);
              // that.chatList[i].record.push(message);
              var record = that.chatList[i];
              record.record.push(message);
              // that.chatList[n].record.push(message);
              that.$set(that.chatList, i, record);
              console.log(
                that.chatList[i].record[that.chatList[i].record.length - 1]
              );
            }
          }

          that.scrollTop();
          that.text = "";
          console.log(that.chatList);
          //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
          console.log("Send successfully");
        },
        onError: function(errorCode, message) {
          var info = "";
          switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
              info = "超时";
              break;
            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
              info = "未知错误";
              break;
            case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
              info = "在黑名单中，无法向对方发送消息";
              break;
            case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
              info = "不在讨论组中";
              break;
            case RongIMLib.ErrorCode.NOT_IN_GROUP:
              info = "不在群组中";
              break;
            case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
              info = "不在聊天室中";
              break;
            default:
              info = x;
              break;
          }
          console.log("发送失败:" + info);
        }
      });
    },
    sumbit() {
      if (this.text != "") {
        this.sendTextMessage(this.text);
        this.clearUnreadCount(this.targetId);
      }
    },
    //清除当前未读数
    clearUnreadCount(targetId) {
      /*
	 	此方法清除当前端的未读数，并不会多端同步，
	 	多端同步需要发送 SyncReadStatusMessage：http://support.rongcloud.cn/kb/NjE0
	 */

      var start = Date.now();
      var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
      RongIMClient.getInstance().clearUnreadCount(conversationtype, targetId, {
        onSuccess: function() {
          console.log("清除未读数成功", "success", start);
        },
        onError: function(error) {
          console.log("清除未读数失败", error, start);
        }
      });
    },
    //获取单一用户消息条数
    getUnreadCount() {
      var that = this;
      /*
		阅读时间戳缓存在 localStorage 中，消息状态根据发送时间和阅读时间戳对比判断
		每次接受新消息后通过重新调用此方法计算
	 */
      var start = new Date().getTime();
      console.log(this.$userId);
      RongIMClient.getInstance().getUnreadCount("PRIVATE", that.userId, {
        onSuccess: function(count) {
          console.log("获取会话未读数成功", count, start);

          // console.log("获取会话未读数成功", count, start);
        },
        onError: function(error) {
          // console.log("获取会话未读数失败", error, start);
        }
      });
    },
    //获取单一用户未读历史消息
    getHistroyMessage() {
      var that = this;
      // alert(1);
      /*
	文档：http://www.rongcloud.cn/docs/web_api_demo.html#获取历史消息

	注意事项：
		1：一定一定一定要先开通 历史消息云存储 功能，本服务收费，测试环境可免费开通
		2：登录开发者后台可以直接开启 https://developer.rongcloud.cn/app
		2：timestrap第二次拉取必须为null才能实现循环拉取
	*/
      for (let n = 0; n < that.chatList.length; n++) {
        console.log(that.chatList);
        if (that.chatList[n].unreadMessageCount != 0) {
          var count = that.chatList[n].unreadMessageCount + 2; // 2 <= count <= 20
          var timestrap = null; //0, 1483950413013
          var conversationType = RongIMLib.ConversationType.PRIVATE;
          var start = new Date().getTime();
          RongIMClient.getInstance().getHistoryMessages(
            conversationType,
            that.chatList[n].targetId,
            timestrap,
            count,
            {
              onSuccess: function(list, hasMsg) {
                //可通过sort订制其他顺序
                list.sort(function(a, b) {
                  return a.sentTime > b.sentTime;
                });
                console.log(list, 222222222);
                for (let s = 0; s < list.length; s++) {
                  list[s].sentTime = timeFormatNotime(list[s].sentTime);
                  list[s].content.content = RongIMLib.RongIMEmoji.emojiToHTML(
                    RongIMLib.RongIMEmoji.symbolToEmoji(list[s].content.content)
                  );
                  var record = that.chatList[n];
                  record.record.unshift(list[s]);
                  console.log(record);
                  that.$set(that.chatList, n, record);
                  // that.chatList[n].record.unshift(list[s]);
                }
                // if (list[s].messageType == "ImageMessage") {
                // setTimeout(function() {
                that.scrollTop();
                // }, 1000);
                // }
                // showResult("获取历史消息成功", list, start);
              },
              onError: function(error) {
                // showResult("获取历史消息失败", error, start);
              }
            }
          );
        } else {
          console.log(444);
        }
      }
    },
    //获取未读消息总条数
    getTotalUnreadCount() {
      var that = this;
      /*
		阅读时间戳缓存在 localStorage 中，消息状态根据发送时间和阅读时间戳对比判断
		每次接受新消息后通过重新调用此方法计算
	 */
      var start = new Date().getTime();
      RongIMClient.getInstance().getTotalUnreadCount({
        onSuccess: function(count) {
          // count == 0
          //   ? that.$notify({
          //       title: "成功",
          //       message: "您暂无未读消息",
          //       type: "success"
          //     })
          //   : that.$notify({
          //       title: "成功",
          //       message: "您有" + count + "条信息未读", 
          //       type: "success"
          //     });
          // console.log("获取总未读数成功", count, start);
        },
        onError: function(error) {
          // console.log("获取总未读数失败", error, start);
        }
      });
    },
    getConversationList(that) {
      var that = that;
      console.log('id=' + that.firmIm)
      /*
	文档：http://www.rongcloud.cn/docs/web_api_demo.html#会话接口
		  http://www.rongcloud.cn/docs/web.html#5_2、同步会话列表
		  http://www.rongcloud.cn/docs/api/js/Conversation.html
	历史消息云存储开通位置：https://developer.rongcloud.cn/service/roam/rXxI4IAJjxRAD72SpQ==
	注意事项：
	  	1：一定一定一定要先开通 历史消息云存储 功能，本服务收费，测试环境可免费开通
		  2：只有发过消息才能生成会话
	  */
      var conversationTypes = null; //具体格式设置需要补充
      var limit = 20; //获取会话的数量，不传或传null为全部，暂不支持分页
      var start = new Date().getTime();
      RongIMClient.getInstance().getConversationList(
        {
          onSuccess: function(list) {
            console.log("重置会话列表");
            // that.chatList = [];
            console.log(that.chatList);
            list.sort(function(a, b) {
              return a.sentTime > b.sentTime;
            });
            var title = "成功获取 " + list.length + " 个会话";
            //修改逻辑如下:判断GetQueryString().firmIm这个id是否存在，如果存在则主动发送'你好'给客户，发送成功后再获取会话列表
            for (let i = 0; i < list.length; i++) {
              list[i].number = 0;
              list[i].record = [];
              if (list[i].targetId == that.firmIm) {
                list[i].check = true;
              } else {
                list[i].check = false;
              }
              for (let n = i + 1; n < list.length; n++) {
                if (list[i].targetId == list[n].targetId) {
                  list[i].number++;
                  list.splice(n, 1); //console.log(arr[j]);
                  n--;
                }
              }
              //获取自己服务器上的头像和昵称
              axios({
                method:"POST",
                url:base_url + "/rongyun/getInfo",
                data:Qs.stringify({
                  userId: list[i].targetId
                }),
                headers:{
                    'Content-Type':'application/x-www-form-urlencoded',
                    "TOKEN":localStorage.getItem('wACCESS_TOKEN')
                }
                })
                .then(function (response) {
                  if (response.data.msg == "success") {
                    list[i].ryName = response.data.data.ryInfo.ryName;
                    list[i].ryIcon = response.data.data.ryInfo.ryIcon;
                  } else {
                    list[i].ryName = "获取失败";
                    list[i].ryIcon = "";
                  }
                })
                .catch(function (error) {
                    console.log(error);
                });
              // that.$ajax
              //   .post(
              //     that.$Url + "/rongyun/getInfo",
              //     that.$qs.stringify({
              //       userId: list[i].targetId
              //     })
              //   )
              //   .then(response => {
              //     if (response.data.msg == "success") {
              //       list[i].ryName = response.data.data.ryInfo.ryName;
              //       list[i].ryIcon = response.data.data.ryInfo.ryIcon;
              //     } else {
              //       list[i].ryName = "获取失败";
              //       list[i].ryIcon = "";
              //     }
              //   })
              //   .catch(function(error) {
              //     console.log(error);
              //   });
            }

            console.log("获取会话列表消息");

            that.chatList = list;
            // console.log();
            that.getHistroyMessage();
            // that.$notify({
            //   title: "成功",
            //   message: title,
            //   type: "success"
            // });
            // console.log(title, list, start);
          },
          onError: function(error) {
            // console.log("获取会话失败", error, start);
          }
        },
        conversationTypes,
        limit
      );
    },
    select(targetId, index) {
      console.log(12132321313213);
      console.log(targetId, index);
      this.targetId = targetId;
      this.activeIndex = index;
      for (let i = 0; i < this.chatList.length; i++) {
        var record = this.chatList[i];
        record.check = false;
        this.$set(this.chatList, i, record);
      }
      var record = this.chatList[index];
      record.check = true;
      this.$set(this.chatList, index, record);
      // this.chatList[index].check = true;
      console.log(this.chatList);
      // this.getHistroyMessage();
      this.clearUnreadCount(targetId);
      this.scrollTop();
    },
    upload() {
      document.querySelector(".img-upload input").click();
    },
    //图片上传成功函数
    upSuccess(response, file, fileList) {
      var that = this;
      if (response.code == 1 && response.msg == "success") {
        let reader = new FileReader(); //html5读文件
        reader.readAsDataURL(that.file); //转BASE64
        reader.onload = function(e) {
          that.base64Data = e.target.result;
          var base64Str = e.target.result.split(";")[1]; //base64
          base64Str = base64Str.split(",")[1];
          // console.log(base64Str);
          // var base64Str = convertImgDataToBlob(e.target.result, that.type); //二进制数据流
          // console.log(base64Str);
          // var base64Str = response.data.imgUrl;
          var imageUri = response.data.imgUrl; // 上传到自己服务器的 URL。
          var msg = new RongIMLib.ImageMessage({
            content: base64Str,
            imageUri: imageUri
          });
          var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
          var targetId = that.firmIm; // 目标 Id
          RongIMClient.getInstance().sendMessage(
            conversationtype,
            targetId,
            msg,
            {
              onSuccess: function(message) {
                console.log(message);
                for (let i = 0; i < that.chatList.length; i++) {
                  if (that.chatList[i].check) {
                    message.sentTime = timeFormatNotime(message.sentTime);
                    // console.log(message.content.content);
                    var record = that.chatList[i];
                    record.record.push(message);
                    that.$set(that.chatList, i, record);
                    // that.chatList[i].record.push(message);
                  }
                }
                that.scrollTop();
                // that.text = "已发送";
                that.text = "";
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                console.log("Send successfully");
              },
              onError: function(errorCode, message) {
                var info = "";
                switch (errorCode) {
                  case RongIMLib.ErrorCode.TIMEOUT:
                    info = "超时";
                    break;
                  case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = "未知错误";
                    break;
                  case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                    info = "在黑名单中，无法向对方发送消息";
                    break;
                  case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                    info = "不在讨论组中";
                    break;
                  case RongIMLib.ErrorCode.NOT_IN_GROUP:
                    info = "不在群组中";
                    break;
                  case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                    info = "不在聊天室中";
                    break;
                  default:
                    info = x;
                    break;
                }
                console.log(info);
                console.log("发送失败:" + info);
              }
            }
          );
        };
      }
    },
    upremove(file, fileList) {}
  }
})




function timeFormatNotime(time) {
  var date = new Date(time),
    curDate = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate(),
    hour = date.getHours(),
    minute = date.getMinutes(),
    curYear = curDate.getFullYear(),
    curHour = curDate.getHours(),
    timeStr;
  if (minute < 10) {
    minute = "0" + minute;
  }
  if (year < curYear) {
    timeStr = year + "年" + month + "月" + day + "日" + hour + ":" + minute;
  } else {
    var pastTime = curDate - date,
      pastH = pastTime / 3600000;

    if (pastH > curHour) {
      timeStr = month + "月" + day + "日 " + "" + hour + "时" + minute + "分";
    } else if (pastH >= 1) {
      timeStr = "今天 " + hour + ":" + minute + "分";
    } else {
      var pastM = curDate.getMinutes() - minute;
      if (pastM > 1) {
        timeStr = pastM + "分钟前";
      } else {
        // timeStr = "刚刚";
        timeStr = hour + ":" + minute + "分";
      }
    }
  }
  return timeStr;
}

function getGet() {
  querystr = window.location.href.split("?");
  if (querystr[1]) {
    let GETs = querystr[1].split("&");
    let GET = [];
    for (i = 0; i < GETs.length; i++) {
      let tmp_arr = GETs.split("=");
      let key = tmp_arr[0];
      GET[key] = tmp_arr[1];
    }
  }
  return querystr[1];
}
/**
 * 分割函数
 */
function GetQueryString() {
  var obj = new Object();
  var scan_url = window.location.href.split("?")[1];
  var strs = scan_url.split("&");
  for (var x in strs) {
    var arr = strs[x].split("=");
    obj[arr[0]] = arr[1];
  }
  return obj;
}

/**
 * 将base64转换成二进制函数
 */
function convertImgDataToBlob(base64Data,type) { 
       var base64 = base64Data;
       var code = window.atob(base64.split(",")[1]);
       var aBuffer = new window.ArrayBuffer(code.length);
       var uBuffer = new window.Uint8Array(aBuffer);
       for (var i = 0; i < code.length; i++) {
           uBuffer[i] = code.charCodeAt(i) & 0xff;
           }
        var blob = null;
          try {
                blob = new Blob([uBuffer], {
                    type: type
                });
          } catch (e) {
              window.BlobBuilder =
              window.BlobBuilder ||
              window.WebKitBlobBuilder ||
              window.MozBlobBuilder ||
              window.MSBlobBuilder;
          if (e.name == "TypeError" && window.BlobBuilder) {
              var bb = new window.BlobBuilder();
              bb.append(uBuffer.buffer);
              blob = bb.getBlob(type);
          } else if (e.name == "InvalidStateError") {
              blob = new Blob([aBuffer], {
              type: type
          });
          } else {}
          }
          return blob;
}